<?php
/**
 * 
 * Session 类
 * @author will
 *
 */
class Session {
	protected $uin = 0;
	protected $skey = null;
	protected $time = 0;				// skey 最后更新的时间
	
	private $timeout = 86400;		// skey 过期时间
	
    /**
     * 
     * 构造函数，初始化 skey
     */
	public function __construct($sid = false) {
		// 获取参数中传入的sid。 先从参数中取，没有的话从 GET 参数中获取，如果没有，则从 POST 参数中获取
		if(empty($sid)) {
			$sid = !empty($_GET['sid']) ? trim($_GET['sid']) : ( isset($_POST['sid']) ? trim($_POST['sid']) : null );
		}

		if(empty($sid)) {
			$this->uin = 0;
			$this->skey = '';
		} else {
			$Db = loadDB();
			$sid = Db::filter($sid);
			$result = $Db->getOne("SELECT * FROM `session` WHERE `skey` = '{$sid}'");
			if(empty($result)) {
				// skey 不存在
				$this->uin = 0;
				$this->skey = '';
				$this->time = 0;
			} else if (($_SERVER['REQUEST_TIME'] - $result['time']) > $this->timeout) {
				// skey 已过期
				$this->uin = 0;
				$this->skey = '';
				$this->time = 0;
			} else {
				// skey 有效
				$this->uin = $result['uin'];
				$this->skey = $result['skey'];
				$this->time = $result['time'];
			}
		}
	}
	
	/**
	 * 获取当前uin
	 */
	public function getUin() {
		return $this->uin;
	}
	
	/**
	 * 获取当前 Session
	 */
	public function getSkey() {
		return $this->skey;
	}
	
	/**
	 * 获取当前 skey 最后更新的时间
	 */
	public function getTime() {
		return $this->time;
	}
	
	/**
	 * 强制生成 skey
	 * @param int $uin
	 */
	public function addSkey($uin = null) {
		if($uin) {
			$this->uin = $uin;
		}
		
		// 判断数据库里是否有当前uin的skey
		$Db = loadDB();
		// $Db->query("DELETE FROM `session` WHERE `uin` = " . $this->uin);
		
		// 生成 skey
		$time = time();
		$skey = $this->genSkey($this->uin , $time);
		$Db->query("INSERT INTO `session` (`skey` , `uin` , `time` ) VALUES ('{$skey}' , {$this->uin} , {$time})");
		
		$this->skey = $skey;
		$this->time = $time;
		
		return $skey;
	}
	
	/**
	 * 删除skey
	 */
	public function deleteSkey() {
		$Db = loadDB();
		$Db->query("DELETE FROM `session` WHERE `skey` = '{$this->skey}'");
		
		$this->uin = 0;
		$this->skey = '';
		$this->time = 0;
				
		return true;
	}
	
	/**
	 * 计算 skey
	 */
	private function genSkey($uin , $time) {
		return 'skey_' . $uin . '_' . $time;
	}
	
	/**
	 * 更新当前 session
	 * @param $limit_time session 时间更新间隔
	 */
	public function update( $limit_time = 30 ) {
		$cur_time = isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time();
		
		// 如果上次更新时间还没超过更新间隔，则不再更新
		if($this->getTime() + $limit_time > $cur_time) {
			return true;
		}
		
		$Db = loadDB();
		$Db->query("UPDATE `session` SET `time` = {$cur_time}  WHERE `skey` = '{$this->skey}'");
		$this->time = $cur_time;
		
		return true;
	}
}


# end of script
